package uam2

import (
	"context"
	"github.com/chromedp/chromedp"
)

type UamStruct struct {
	url          string
	username     string
	pwd          string
	ctx          context.Context
	cancel       context.CancelFunc
	newCtx       context.Context
	token        string
	remoteLoginC chan int
}

func (s *UamStruct) Run() error {
	return chromedp.Run(s.ctx, chromedp.Tasks{
		s.MyFuncListenTarget(),
		s.MyFuncRegisterNewTarget(),
		chromedp.Navigate(s.url),
		s.userLogin(),
		chromedp.Click(`document.getElementsByClassName("ant-btn ant-btn-primary ant-btn-background-ghost mx-2")[0]`, chromedp.ByJSPath),
		s.MyFuncListenQuit(),
	})
}

func New(headless bool) *UamStruct {
	s := &UamStruct{
		url:          "http://192.168.51.212:60000",
		username:     "hcy",
		pwd:          "123456Ab",
		remoteLoginC: make(chan int, 1),
	}
	options := []chromedp.ExecAllocatorOption{
		chromedp.Flag("headless", headless), // 是否打开浏览器调试
		chromedp.UserAgent("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"), // 设置User-Agent
	}
	options = append(chromedp.DefaultExecAllocatorOptions[:], options...)
	// chromdp依赖context上限传递参数
	s.ctx, s.cancel = chromedp.NewExecAllocator(
		context.Background(),
		options...,
	)
	s.ctx, s.cancel = chromedp.NewContext(
		s.ctx,
	)
	return s
}
